# 此脚本用于刷面试报告数据
# 报告数据有更新时运行该脚本

import time
import redis
import requests
from sqlalchemy import create_engine, Column, Integer, DateTime, String
from sqlalchemy.orm import sessionmaker, DeclarativeBase

ENV = 'test'
DATABASE_URL = "mysql://youshi_t:2K4adice?sdfrx3e@10.9.93.161/peilian_test_zs"
if ENV == 'prod':
    DATABASE_URL = "mysql://youshi:1G?ywxyrlis4Orl@10.9.93.161/peilian"


class Base(DeclarativeBase):
    pass


class Report(Base):
    __tablename__ = 'session'

    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    career_name = Column(String)
    url = Column(String)


def main():
    redis_key = f'flush_data_list_queue'
    r = redis.Redis(host='127.0.0.1', port=6379, decode_responses=True)
    if r.llen(redis_key) <= 0:
        engine = create_engine(DATABASE_URL)
        session_cls = sessionmaker(bind=engine)
        session = session_cls()
        career_list = [
            '通用能力', '产品经理', '项目经理', '互联网运营', '游戏策划', '市场营销', '销售', '行政',
            '人力资源', '财务', '银行管培生', '通用岗位'
        ]
        query = session.query(Report).filter(Report.career_name.in_(career_list)).order_by(Report.id)
        results = query.all()
        session.close()
        for row in results:
            if row.url and row.career_name in career_list:
                r.lpush(redis_key, row.id)

    while True:
        report_id = r.lpop(redis_key)
        if report_id is None:
            break
        req_url = f'https://growup-test.aminer.cn/api/practice/session/{report_id}/report'
        if ENV == 'prod':
            req_url = f'https://growup.aminer.cn/api/practice/session/{report_id}/report'
        try:
            resp = requests.post(
                url=req_url,
                json={
                    'session_Id': f'{report_id}'
                },
                headers={'AuthenticationToken': "AMiner123@"}
            )
            print(resp.json(), report_id, '\n\n')
        except Exception as e:
            print(e)
            r.lpush(redis_key, report_id)
            continue
        time.sleep(20)


if __name__ == '__main__':
    main()
